const path = require("path");
const BaseHandler = require(path.join(__dirname, "../libs/baseHandler.js"));
const handler = new BaseHandler();
const User = require("../models/users");
const { signTokenByUsername, comparePasswordSync } = require("../libs/auth");

handler.getA = async function (ctx) {
  return handler.restSuccess(ctx, { res: "a" });
};

handler.login = async function (ctx) {
  const { username, password } = ctx.request.body;
  const user = await User.findOne({ username });
  if (!user) {
    throw new Error("用户名或密码错误！");
  }

  const pwd = user.password;
  const isCorrect = comparePasswordSync(password, pwd);

  if (isCorrect) {
    const token = signTokenByUsername(username);
    return handler.restSuccess(ctx, { username, token, userId: user._id });
  } else {
    throw new Error("用户名或密码错误！");
  }
};

module.exports = handler;
